<?php

namespace App\Services\ApplyGoldWastesSubsidy;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class ApplyGoldWastesSubsidy
{
    protected User $user;

    public function __construct(User  $user)
    {
        $this->user = $user;
    }

    public function execute()
    {
        $user = $this->user;
        $money = big_decimal($user->myAllGoldWastesMoney());

        if ($money->isLessThanOrEqualTo(0)) return;

        DB::transaction(function () use ($user, $money) {
            account_subsidies($user)->plusInitialSubsidies($money);
            account_cashes($user)->plusInitialCashes($money->multipliedBy(2));
            $user->goldWastes()->delete();
            $user->update(['gold_wastes_subsidy_at' => Carbon::now()]);
        });
    }

    public function apply()
    {
        $this->execute();
    }
}
